package com.runfast.waimai.web.controller;

import com.runfast.common.dao.model.RunfastCuser;
import com.runfast.common.security.spring.UserDataDetails;
import com.runfast.common.service.RunfastCuserService;
import com.runfast.common.utils.TokenUtil;
import com.runfast.common.web.entity.Result;
import com.runfast.common.web.entity.ResultCode;
import com.runfast.pay.Channel;
import com.runfast.waimai.dao.model.*;
import com.runfast.waimai.service.*;
import com.runfast.waimai.task.async.MessagePushTask;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 我的钱包接口
 */
@RestController("userWmWalletController")
@RequestMapping(value= "/api/user/wm/wallet", headers = "token")
public class WalletController {


    @Autowired
    private RunfastBankaccountsService bankaccountsService;

    @Autowired
    private RunfastCuserService cuserService;

    @Autowired
    private RunfastWithdrawService withdrawService;

    @Autowired
    private RunfastAccountrecordService accountrecordService;

    @Autowired
    private RunfastGoodsSellRecordService orderService;


    @Autowired
    private RunfastGoodsSellOutStatusService statusService;

    @Autowired
    private MessagePushTask messagePushTask;

    /**
     * 收支明细列表
     * @param token
     * @return
     */
    @PostMapping("/inOutDetail")
    public Result<List<RunfastAccountrecord>> inOutDetail(@RequestHeader String token) {
        Integer userId = TokenUtil.getUserId(token);


        List<Integer> typeList = new ArrayList<>();
        typeList.add(0);
        typeList.add(3);
        typeList.add(4);
        RunfastAccountrecordExample accountrecordExample = new RunfastAccountrecordExample();
        accountrecordExample.or().andCidEqualTo(userId).andTypeIn(typeList);
        accountrecordExample.setOrderByClause("id desc");
        List<RunfastAccountrecord> accountrecordList = accountrecordService.selectByExample(accountrecordExample);

        return Result.ok("",accountrecordList);
    }


    /**
     * 提现申请
     * @param amountWithdraw 提现金额
     * @param bankAccountId 银行卡账户
     * @param token
     * @return
     */
    @PostMapping("/withdraw")
    public Result withdraw(@RequestParam BigDecimal amountWithdraw, @RequestParam int bankAccountId,@RequestParam String remark, @RequestHeader String token) {
        Integer userId = TokenUtil.getUserId(token);

        if(amountWithdraw.compareTo(BigDecimal.valueOf(0))!=1) return Result.fail(ResultCode.FAIL, "提现金额必须大于零");

        RunfastBankaccountsExample bankaccountsExample = new RunfastBankaccountsExample();
        bankaccountsExample.or().andIdEqualTo(bankAccountId).andUserIdEqualTo(userId);
        List<RunfastBankaccounts> bankaccountsList = bankaccountsService.selectByExample(bankaccountsExample);
        if(bankaccountsList.isEmpty()) return Result.fail(ResultCode.FAIL, "不存在该银行卡账户");
        RunfastBankaccounts bankaccounts = bankaccountsList.get(0);

        RunfastCuser cuser = cuserService.selectByPrimaryKey(userId);
        BigDecimal remainder = cuser.getRemainder();
        remainder = remainder==null?BigDecimal.valueOf(0):remainder;

        /*RunfastWithdrawExample withdrawExample = new RunfastWithdrawExample();
        withdrawExample.or().andUserIdEqualTo(userId).andApplytypeEqualTo(1).andTypeEqualTo(2).andStatusEqualTo(0);
        List<RunfastWithdraw> withdrawList = withdrawService.selectByExample(withdrawExample);
        BigDecimal amountApply = BigDecimal.valueOf(0);
        for (RunfastWithdraw withdraw : withdrawList) {
            amountApply.add(withdraw.getMonetary());
        }*/

        if(remainder.compareTo(amountWithdraw) ==-1){

            return Result.fail(ResultCode.FAIL, "余额不足");
        }else{

            RunfastWithdraw withdraw = new RunfastWithdraw();
            withdraw.setContent(remark);
            withdraw.setMonetary(amountWithdraw);
            withdraw.setCreateTime(new Date());
            withdraw.setType(2);
            withdraw.setStatus(0);
            withdraw.setState(0);
            withdraw.setApplytype(1);
            withdraw.setUserId(userId);
            withdraw.setUserMobile(cuser.getMobile());
            withdraw.setUserName(cuser.getName());


            withdraw.setBankid(bankAccountId);
            withdraw.setBanktype(bankaccounts.getBanktype());
            withdraw.setName(bankaccounts.getName());
            withdraw.setAccount(bankaccounts.getAccount());

            withdrawService.insertSelective(withdraw);


            RunfastCuser cuserUpdate = new RunfastCuser();
            cuserUpdate.setId(cuser.getId());
            cuserUpdate.setRemainder(remainder.subtract(amountWithdraw));

            cuserService.updateByPrimaryKeySelective(cuserUpdate);

            return Result.ok("申请已提交，2个工作日内审核处理请耐心等待");

        }



    }


    /**
     * 提现记录
     * @param pageable
     * @param token
     * @return
     */
    @PostMapping("/withdrawRecord")
    public Result<List<RunfastWithdraw>> withdrawRecord(@PageableDefault Pageable pageable, @RequestHeader String token) {
        Integer userId = TokenUtil.getUserId(token);


        RunfastWithdrawExample withdrawExample = new RunfastWithdrawExample();
        withdrawExample.or().andUserIdEqualTo(userId).andApplytypeEqualTo(1).andTypeEqualTo(2);
        withdrawExample.setOrderByClause("id desc");
        List<RunfastWithdraw> withdrawList = withdrawService.selectByExampleWithPageable(withdrawExample,pageable);
        return Result.ok("", withdrawList);
    }







}
